import logging
import os
import json
from logging.handlers import RotatingFileHandler
from core.config.config import LogConfig
from core.logger.logging import CustomLogFormatter, CustomLogger
from typing import Optional


class _LoggerProxy:
    _val: Optional[CustomLogger] = None

    def __getattr__(self, name: str):
        if self._val is None:
            raise RuntimeError("logger 未初始化：请先调用 init_logger(...)")
        return getattr(self._val, name)


logger = _LoggerProxy()


def init_logger(name: str, log_cfg: LogConfig) -> CustomLogger:
    log = logging.getLogger(name)
    log.setLevel(log_cfg.level)

    formatter = CustomLogFormatter()
    # 文件日志
    log_dir = os.path.dirname(log_cfg.path)
    os.makedirs(log_dir, exist_ok=True)
    file_handler = RotatingFileHandler(
        log_cfg.path, maxBytes=5 * 1024 * 1024, backupCount=5, encoding="utf-8"
    )
    file_handler.setFormatter(formatter)

    log.addHandler(file_handler)
    logger._val = CustomLogger(log)
    return logger._val  # 返回 CustomLogger 实例
